package cn.caipengbo.shoppingcart;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 鹏博 on 1/20/2017.
 */
@WebServlet(name = "ShoppingCart")
public class ShoppingCart extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //根据name获得商品名称(数组实现)
        String[] products = new String[]{"商品0","商品1","商品2","商品3"};
        int intIndex = Integer.parseInt(request.getParameter("index"));
        String productName = products[intIndex];
        // 获得session
        HttpSession session = request.getSession();
        //从session中取出一个Attribute <"car",Map<String,Integer>>（这是购物车attribute，session中还会有其他attribute）
        Map<String,Integer> map = (Map<String, Integer>) session.getAttribute("car");
        //不存在(购物车为空)
        if (map == null){
            map = new HashMap<String,Integer>();
            map.put(productName,1);
        } else {
            Integer count = map.get(productName);
            if (count == null) {
                //不存在的商品数目为1
                count = 1;
            } else {
                //存在的商品数目增加
                count++;
            }
            map.put(productName,count);
        }
        //将map放入session
        session.setAttribute("car",map);
        //返回商品列表页  注意路径
        response.sendRedirect("/JavaWeb/shoppingcart/shoplist.jsp");
    }
}
